package com.wang.helloworld.zookeeper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * Hello world!
 *
 */
public class HelloZookeeper 
{
	final static String zookeeper_connection = "dev.findsing.com:2181";
	static ZooKeeper zookeeper;
	final static int SESSION_TIME = 30000;

	public static void main(String[] args) throws IOException, KeeperException, InterruptedException
    {
		new HelloZookeeper(zookeeper_connection);
    }

	public HelloZookeeper(String zookeeper_connection) throws IOException, KeeperException, InterruptedException
	{
		Watcher watcher = new ZookeeperWatcher();
		zookeeper = new ZooKeeper(zookeeper_connection, SESSION_TIME, watcher);
		printPath(zookeeper, watcher);

		Scanner console = new Scanner(System.in);
		do{
			System.out.print("> ");
			String command = console.nextLine();
			if(command.equals("exit"))
			{
				try {
					zookeeper.close();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally
				{
					return;
				}
			}
		}while(true);
	}
	
	public void printPath(ZooKeeper zookeeper, Watcher watcher) throws KeeperException, InterruptedException
	{
		printPath("/", 0, zookeeper, watcher);
	}

	public void printPath(String parent, int deep, ZooKeeper zookeeper, Watcher watcher) throws KeeperException, InterruptedException
	{
		Stat nodeStatus = new Stat();
		byte[] nodeData = zookeeper.getData(parent, watcher, nodeStatus);
		printMargin(deep, "  ");System.out.println("{");
		printMargin(deep, "  ");System.out.println("Node status: [" + nodeStatus.toString().trim() + "]");
		try {
			if (null !=nodeData ) {
				printMargin(deep, "  ");System.out.println("Node data: ["+ /*Arrays.toString(nodeData)*/new String(nodeData,"UTF-8") + "]");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		printMargin(deep, "  ");System.out.println("}");
		
		
		List<String> folders = zookeeper.getChildren(parent, watcher);
		for(String folder: folders)
		{
			printMargin(deep, "--");
			System.out.println(folder);

			printPath((parent.equals("/")?parent:(parent + "/"))+folder, deep+1, zookeeper, watcher);
		}
	}
	
	public void printMargin(int level, String tab)
	{
		for(int i=0; i<level; i++){
			System.out.print(tab);
		}
	}
}
